# -*- coding: utf-8 -*-
"""
Task23.

Usage:
  task23.py -f <file_names> ...

Options:
  -h --help     Show this screen.
  --version     Show version.
  -f            File names.
"""

import sys

modules = ["os", "docopt", "Bio"]
exit_flag = False
for module in modules:
    try:
        __import__(module)
    except ImportError:
        exit_flag = True
        sys.stderr.write("Error: Python module " + module + " is not installed.\n")
        
if exit_flag:
    sys.exit("Some required Python modules are not installed.")
    
import os
from docopt import docopt
from Bio import SeqIO
from Bio import SeqUtils
from Bio.Align.Applications import ClustalwCommandline
from Bio import AlignIO

def is_non_zero_file(fpath):  
    return True if os.path.isfile(fpath) and os.path.getsize(fpath) > 0 else False
    
def read_genome(f):
    print
    print f
    print
    f_suffix = f[::-1].split('.')[0][::-1]
    if f_suffix == 'fasta':
        f_format = 'fasta'
    elif f_suffix == 'gb':
        f_format = 'genbank'
    else:
        sys.exit("Error: file " + f + " has unknown format.")
        
    return SeqIO.read(f, f_format)

def calc_gc_content(genome):
    return SeqUtils.GC(genome.seq)
    
def transcribe_genome(genome):
    return genome.seq.transcribe()
    
def translate_genome(genome):
    return rna.translate()

if __name__ == '__main__':
    arguments = docopt(__doc__, version='Cont 0.1')
    if not arguments['-f']:
        sys.exit('Error: file names must be presented (-f option).')
    else:
        files = arguments['<file_names>']
        for f in files:
            if not is_non_zero_file(f):
                sys.exit('Error: file ' + f + ' is empty or does not exist.')
    
    print "Processing started..."
    
    with open('proteins.fasta', 'w') as tmp:
        pass
    
    protein_seqs = []
    for f in files:
        with open('proteins.fasta', 'a') as tmp:
                genome = read_genome(f) 
    
                gc_content = calc_gc_content(genome)            
                print 'GC content: ' + str(round(gc_content, 2)) + '%'
                print
                
                rna = transcribe_genome(genome)
                print 'RNA:', rna
                
                print
                protein = translate_genome(genome)
                print 'Protein:', protein
                
                tmp.write('>' + ((f.split('/'))[::-1])[0] + '\n')
                tmp.write(str(genome.seq))
                tmp.write('\n')

    cline = ClustalwCommandline("clustalw", infile="proteins.fasta", 
                                matrix='BLOSUM62')            
    cline()
    align = AlignIO.read("proteins.aln", "clustal")
    print
    print 'Alignment shortcut:'
    print
    print align
    print
    print 'Full alignment:'
    print
    with open('proteins.aln', 'r') as pr:
        for line in pr:
            print line,
    print
    
    align = AlignIO.read("proteins.aln", "clustal")
    AlignIO.write(align, "proteins.phy", "phylip")
    
    print "Processing is finished."
    